﻿#include "station.h"
#include "ui_station.h"
#include <QFile>
#include <QDebug>
#include <QWebEngineView>
#include <QWebChannel>
#include "qcustomplot.h"
#include "SignalProcessor.h"
#include <QOpenGLContext>
#pragma execution_character_set("utf-8")

Station::Station(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Station)
{
    ui->setupUi(this);
    // 设置窗口标志并保留最小化和关闭按钮
    this->setWindowFlags(Qt::Window);
    // 使用SignalProcessor类处理数据
    processor = new SignalProcessor(fc, fs, T, snr);


    // 设置全屏
    // this->showFullScreen();

    // 初始化并设置QTableWidget
    setupTableWidget();

    // 初始化UdpHandler
    udpHandler = new UdpHandler(this);
    connect(udpHandler, &UdpHandler::dataReceived, this, &Station::handleDataReceived);
    connect(ui->clean_button, &QPushButton::clicked, this, &Station::on_clean_server_clicked);
    initMap();  // 初始化地图
    initsetting();
}
bridge::bridge(QObject *parent) : QObject(parent)
{
}
void bridge::RcvPoint(const QString &lng, const QString &lat)
{
    qDebug()<<lng<<","<<lat;
    emit DisplayPoint(lng,lat);
}

Station::~Station()
{
    delete ui;
}
void Station::setupTableWidget()
{
    ui->tableWidget->setColumnCount(6);  // 设置列数

    // 设置水平表头标签
    ui->tableWidget->setHorizontalHeaderLabels(QStringList()<< "飞机横滚角"<< "飞机俯仰角"<< "飞机方向角"<< "海拔高度"<< "相对高度"<< "天向速度");


    // 设置列宽
    for (int i = 0; i < 6; ++i) {
        ui->tableWidget->setColumnWidth(i, 80);
    }

    // 设置不可编辑
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // 设置水平和垂直表头的对齐方式
    ui->tableWidget->horizontalHeader()->setDefaultAlignment(Qt::AlignCenter);
    ui->tableWidget->verticalHeader()->setDefaultAlignment(Qt::AlignCenter);
}

void Station::initMap(){
    // 创建一个与网页交互的通道
    bridge *JSBridge = new bridge(this);
    QWebChannel *channel = new QWebChannel(this);
    channel->registerObject("window",(QObject*)JSBridge);
    ui->MapWidget->page()->setWebChannel(channel);
    // 加载网页，注意加载网页必须在通道注册之后，其有有一个注册完成的信号，
    // 可根据需要调用
    ui->MapWidget->page()->load(QUrl("qrc:/resources/test.html"));
    connect(ui->MapWidget, &QWebEngineView::loadFinished, this, [](bool success){
        if (success) {
            qDebug() << "HTML file loaded successfully.";
        } else {
            qDebug() << "Failed to load HTML file.";
        }
    });
}

void Station:: initsetting(){
    // 右键菜单自定义
    ui->customplot->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->customplot, &QCustomPlot::customContextMenuRequested, this, &Station::contextMenuRequest);
    QCustomPlot* customPlot = ui->customplot;


    customPlot->setBackground(QColor(35, 35, 35));
    customPlot->xAxis->setLabelColor(QColor(255, 255, 255));
    customPlot->yAxis->setLabelColor(QColor(255, 255, 255));
    customPlot->xAxis->setTickLabelColor(QColor(255, 255, 255));
    customPlot->yAxis->setTickLabelColor(QColor(255, 255, 255));
    customPlot->axisRect()->setupFullAxesBox();
    customPlot->xAxis->setLabel("频率/Hz");
    customPlot->yAxis->setLabel("功率/dBm");

    QVector<double> x = processor->linSpace(fs / fft_num, 0, fs);
    QVector<double> sig1RealValues = processor->generateSignalRealValues();
    QVector<double> sig1ImagValues = processor->generateSignalImagValues();

    // 创建图形并设置数据
    customPlot->addGraph();
    customPlot->graph(0)->setData(x, sig1RealValues);
    customPlot->addGraph();
    customPlot->graph(1)->setData(x, sig1ImagValues);


    // 设置样式
    customPlot->graph(0)->setPen(QPen(Qt::blue, 2));
    customPlot->graph(1)->setPen(QPen(Qt::red, 2));
    customPlot->graph(0)->setLineStyle(QCPGraph::LineStyle::lsLine);
    customPlot->graph(1)->setLineStyle(QCPGraph::LineStyle::lsLine);

    // 自动调整范围与交互设置
    customPlot->graph(0)->rescaleAxes();
    customPlot->graph(1)->rescaleAxes(true);
    customPlot->graph(0)->setSelectable(QCP::SelectionType::stMultipleDataRanges);
    customPlot->graph(1)->setSelectable(QCP::SelectionType::stMultipleDataRanges);
    customPlot->setSelectionRectMode(QCP::SelectionRectMode::srmNone);
    customPlot->selectionRect()->setPen(QPen(Qt::black, 1, Qt::DashLine));
    customPlot->selectionRect()->setBrush(QBrush(QColor(0, 0, 100, 50)));

    //滚动缩放、图表可选、多选
    customPlot->setInteractions(QCP::iRangeZoom | QCP::iSelectPlottables| QCP::iMultiSelect);
    customPlot->setOpenGl(true);
    customPlot->replot();
    qDebug()<<"opengle="<<customPlot->openGl();
    // qDebug() << "OpenGL version:" << QOpenGLContext::currentContext()->format().version();
}

void Station::rescaleAxes()
{
    QCustomPlot* customPlot=ui->customplot;
    customPlot->graph(0)->rescaleAxes();
    customPlot->graph(1)->rescaleAxes(true);
    //    customPlot->graph(2)->rescaleAxes(true);
    customPlot->replot();
}
//右键菜单
void Station::contextMenuRequest(QPoint pos)
{
    QCustomPlot* customPlot=ui->customplot;
    QMenu *menu = new QMenu(this);
    menu->setAttribute(Qt::WA_DeleteOnClose);
    menu->addAction("调整范围",this, SLOT(rescaleAxes()));
    menu->popup(customPlot->mapToGlobal(pos));
}
void Station::on_btn_listen_clicked()
{
    if (ui->btn_listen->text() == "侦听")
    {
        udpHandler->startListen();
        ui->btn_listen->setText("取消侦听");
    }
    else
    {
        udpHandler->stopListening();
        ui->btn_listen->setText("侦听");
    }
}
void Station::on_clean_server_clicked()
{
    ui->tableWidget->setRowCount(1); // 清空表格
}
void Station::handleDataReceived(const FlightData &flightData, const QHostAddress &address, quint16 port)
{
    // 添加数据到QTableWidget
    int row = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(row);

    ui->tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(flightData.roll * 0.1)));
    ui->tableWidget->setItem(row, 1, new QTableWidgetItem(QString::number(flightData.pitch * 0.1)));
    ui->tableWidget->setItem(row, 2, new QTableWidgetItem(QString::number(flightData.heading * 0.1)));
    // ui->tableWidget->setItem(row, 3, new QTableWidgetItem(QString::number(flightData.latitude / 10000000.0, 'f', 7)));
    // ui->tableWidget->setItem(row, 4, new QTableWidgetItem(QString::number(flightData.longitude / 10000000.0, 'f', 7)));
    ui->tableWidget->setItem(row, 3, new QTableWidgetItem(QString::number(flightData.gpsAltitude * 0.1)));
    ui->tableWidget->setItem(row, 4, new QTableWidgetItem(QString::number(flightData.relativeAltitude * 0.1)));
    // ui->tableWidget->setItem(row, 7, new QTableWidgetItem(QString::number(flightData.year)));
    // ui->tableWidget->setItem(row, 8, new QTableWidgetItem(QString::number(flightData.month)));
    // ui->tableWidget->setItem(row, 9, new QTableWidgetItem(QString::number(flightData.day)));
    // ui->tableWidget->setItem(row, 10, new QTableWidgetItem(QString::number(flightData.hour)));
    // ui->tableWidget->setItem(row, 11, new QTableWidgetItem(QString::number(flightData.minute)));
    // ui->tableWidget->setItem(row, 12, new QTableWidgetItem(QString::number(flightData.second)));
    // ui->tableWidget->setItem(row, 13, new QTableWidgetItem(QString::number(flightData.eastSpeed * 0.1)));
    // ui->tableWidget->setItem(row, 14, new QTableWidgetItem(QString::number(flightData.northSpeed * 0.1)));
    ui->tableWidget->setItem(row, 5, new QTableWidgetItem(QString::number(flightData.upSpeed * 0.1)));
}
